package backed.controller;

import backed.entity.Order;
import backed.entity.SecondHandItem;
import backed.service.OrderService;
import backed.service.SecondHandItemService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "订单管理", description = "订单创建、支付、确认收货、取消和查询相关接口")
@RestController
@CrossOrigin
@RequestMapping("/api/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private SecondHandItemService secondHandItemService;

    @Operation(summary = "创建订单", description = "根据商品ID、买家ID和收货地址创建新订单")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "创建成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "参数错误或商品不存在")
    })
    @PostMapping("/create")
    public Map<String, Object> createOrder(
            @Parameter(description = "订单信息，包含itemId、buyerId和shippingAddress字段", required = true) 
            @RequestBody Order order){
        Long itemId = order.getItemId();
        Long buyerId = order.getBuyerId();
        String shippingAddress = order.getShippingAddress();

        // 调用服务层创建订单
        Order newOrder = orderService.create(itemId, buyerId, shippingAddress);
        
        // 构建符合API文档要求的响应数据
        Map<String, Object> data = new HashMap<>();
        data.put("orderNo", newOrder.getOrderNo());
        data.put("amount", newOrder.getAmount());
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", data);
        
        return result;
    }

    @Operation(summary = "确认收货", description = "买家确认收货，更新订单状态为已完成")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "确认收货成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "订单状态不正确或订单不存在")
    })
    @PostMapping("/confirm/{orderNo}")
    public Map<String, Object> confirmOrder(
            @Parameter(description = "订单号", required = true, example = "ORD202411150001") 
            @PathVariable("orderNo") String orderNo) {
        Map<String, Object> result = new HashMap<>();
        try {
            Order confirmedOrder = orderService.confirmOrder(orderNo);
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", confirmedOrder.getOrderNo());
            data.put("status", confirmedOrder.getStatus());
            data.put("completeTime", confirmedOrder.getCompleteTime());
            
            result.put("success", true);
            result.put("data", data);
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "确认收货失败");
        }
        return result;
    }

    @Operation(summary = "取消订单", description = "取消未支付或未发货的订单")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "取消订单成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "订单状态不允许取消或订单不存在")
    })
    @PostMapping("/cancel/{orderNo}")
    public Map<String, Object> cancelOrder(
            @Parameter(description = "订单号", required = true, example = "ORD202411150001") 
            @PathVariable("orderNo") String orderNo) {
        Map<String, Object> result = new HashMap<>();
        try {
            Order cancelledOrder = orderService.cancelOrder(orderNo);
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", cancelledOrder.getOrderNo());
            data.put("status", cancelledOrder.getStatus());
            
            result.put("success", true);
            result.put("data", data);
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "取消订单失败");
        }
        return result;
    }

    @Operation(summary = "支付订单", description = "支付指定订单")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "支付成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "订单状态不正确或订单不存在")
    })
    @PostMapping("/pay/{orderNo}")
    public Map<String, Object> payOrder(
            @Parameter(description = "订单号", required = true, example = "ORD202411150001") 
            @PathVariable("orderNo") String orderNo){
        Map<String, Object> result = new HashMap<>();

        Order paidOrder = orderService.payOrder(orderNo);

        Map<String, Object> data = new HashMap<>();
        data.put("orderNo", paidOrder.getOrderNo());
        data.put("status", paidOrder.getStatus());
        data.put("payTime", paidOrder.getPayTime());
        
        result.put("success", true);
        result.put("data", data);
        
        return result;
    }
    
    @Operation(summary = "发货", description = "卖家发货，更新订单状态为已发货")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "发货成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "订单状态不正确或订单不存在")
    })
    @PostMapping("/ship/{orderNo}")
    public Map<String, Object> shipOrder(
            @Parameter(description = "订单号", required = true, example = "ORD202411150001") 
            @PathVariable("orderNo") String orderNo){
        Map<String, Object> result = new HashMap<>();
        try {
            Order shippedOrder = orderService.shipOrder(orderNo);
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", shippedOrder.getOrderNo());
            data.put("status", shippedOrder.getStatus());
            
            result.put("success", true);
            result.put("data", data);
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "发货失败");
        }
        return result;
    }
    @Operation(summary = "获取订单详情", description = "根据订单号查询订单详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "404", description = "订单不存在")
    })
    @GetMapping("detail/{orderNo}")
    public Map<String, Object> detail(
            @Parameter(description = "订单号", required = true, example = "ORD202411150001") 
            @PathVariable("orderNo") String orderNo){
        Map<String, Object> result = new HashMap<>();
        Order order = orderService.findByOrderNo(orderNo).orElse(null);
        if(order == null){
            result.put("success", false);
            result.put("message", "订单不存在");
            return result;
        }
        SecondHandItem item = secondHandItemService.getItemInfo(order.getItemId());
        Map<String, Object> data = new HashMap<>();
        data.put("orderNo", order.getOrderNo());
        data.put("amount", order.getAmount());
        data.put("payTime", order.getPayTime());
        data.put("itemTitle", item.getTitle());
        result.put("success", true);
        result.put("data", data);
        return result;
    }
    @Operation(summary = "获取订单列表", description = "根据用户ID和类型查询订单列表")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "参数错误，type只能是buy或sell")
    })
    @Parameters({
            @Parameter(name = "userId", description = "用户ID", required = true, example = "1"),
            @Parameter(name = "type", description = "订单类型，buy表示购买订单，sell表示销售订单", required = true, example = "buy")
    })
    @GetMapping("/list")
    public Map<String, Object> list(@RequestParam("userId") Long userId,
                                    @RequestParam("type") String type){
        Map<String, Object> result = new HashMap<>();
        String normalizedType = type == null ? "" : type.trim().toLowerCase();
        if (!"buy".equals(normalizedType) && !"sell".equals(normalizedType)) {
            result.put("success", false);
            result.put("message", "type 参数仅支持 buy 或 sell");
            return result;
        }

        List<Order> orders = orderService.listByUserAndType(userId, normalizedType);
        List<Map<String, Object>> items = orders.stream().map(order -> {
            Map<String, Object> itemData = new HashMap<>();
            itemData.put("orderNo", order.getOrderNo());
            itemData.put("itemId", order.getItemId());
            itemData.put("amount", order.getAmount());
            itemData.put("status", order.getStatus());
            itemData.put("createTime", order.getCreateTime());
            itemData.put("buyerId", order.getBuyerId());
            itemData.put("sellerId", order.getSellerId());
            SecondHandItem item = secondHandItemService.getItemInfo(order.getItemId());
            if (item != null) {
                itemData.put("itemTitle", item.getTitle());
                itemData.put("itemPrice", item.getPrice());
                itemData.put("itemImages", item.getImages());
            }
            return itemData;
        }).collect(Collectors.toList());

        Map<String, Object> data = new HashMap<>();
        data.put("total", items.size());
        data.put("items", items);
        result.put("success", true);
        result.put("data", data);
        return result;
    }


}
